package appcus

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/app"
	"counter-help/admin/server/model/audit"
	"counter-help/admin/server/model/customer"
	customerReq "counter-help/admin/server/model/customer/request"
	customerRes "counter-help/admin/server/model/customer/response"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"math/rand"
	"strings"
	"time"
)

type AppUserService struct{}

// 随机生成 8 位字符串作为用户名
func generateRandomUsername(length int) string {
	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	result := strings.Builder{}
	for i := 0; i < length; i++ {
		result.WriteByte(charset[rand.Intn(len(charset))])
	}
	return result.String()
}

// 处理
func (a *AppUserService) Login(u *app.AppUser) (userInter *app.AppUser, err error) {
	var existingUser app.AppUser

	// 检查用户是否已注册
	if err := global.GVA_DB.Model(&app.AppUser{}).Where("phone = ?", u.Phone).Or("unionid = ?", u.Unionid).
		First(&existingUser).Error; err == nil {
		if existingUser.Phone == "" {
			global.GVA_DB.Model(&app.AppUser{}).Where("id = ?", existingUser.ID).Update("phone", u.Phone)
		}
		if existingUser.Openid == "" {
			global.GVA_DB.Model(&app.AppUser{}).Where("id = ?", existingUser.ID).Update("openid", u.Openid)
		}
		// 用户已注册
		return &existingUser, nil
	} else if !errors.Is(err, gorm.ErrRecordNotFound) {
		// 查询过程中发生其他错误
		return nil, err
	}

	// 自动生成随机用户名和固定密码
	var user customer.CusUser
	user.Phone = u.Phone
	user.Unionid = u.Unionid
	user.Openid = u.Openid
	user.Nickname = u.NickName
	user.Birth = u.Birth
	user.Address = u.Address
	user.Username = generateRandomUsername(8) // 随机生成 8 位用户名
	user.Password = "123456"
	// 用户未注册，创建用户
	err = global.GVA_DB.Create(&user).Error
	if err != nil {
		return nil, err
	}

	return u, nil
}

func (appUserService *AppUserService) GetUsersByIDList(userIDs []int) ([]customerRes.CusUserDetailsResponse, error) {
	var users []customer.CusUser

	// 查询基本的用户信息
	err := global.GVA_DB.Model(&customer.CusUser{}).
		Where("id IN ?", userIDs).
		Find(&users).Error
	if err != nil {
		return nil, err
	}

	// 查询 EducationVerification 表，获取 degree 和 school_name
	var educationVerifications []struct {
		UserID     int
		Degree     string
		SchoolName string
	}
	err = global.GVA_DB.Model(&audit.EducationVerification{}).
		Where("user_id IN ?", userIDs).
		Select("user_id, degree, school_name").
		Find(&educationVerifications).Error
	if err != nil {
		return nil, err
	}

	// 创建一个 map，用于快速查找用户的 education 信息
	educationMap := make(map[int]struct {
		Degree     string
		SchoolName string
	})
	for _, edu := range educationVerifications {
		educationMap[edu.UserID] = struct {
			Degree     string
			SchoolName string
		}{edu.Degree, edu.SchoolName}
	}

	// 查询 TechnicalVerification 表，标记是否有技术认证
	var technicalVerifications []struct {
		UserID int
	}
	err = global.GVA_DB.Model(&audit.TechnicalVerification{}).
		Where("user_id IN ?", userIDs).
		Select("user_id").
		Find(&technicalVerifications).Error
	if err != nil {
		return nil, err
	}

	// 将技术认证结果存入 map，便于查询
	technicalMap := make(map[int]bool)
	for _, tech := range technicalVerifications {
		technicalMap[tech.UserID] = true
	}

	// 查询 UserIdentity 表，标记是否有身份认证
	var userIdentities []struct {
		UserID int
	}
	err = global.GVA_DB.Model(&audit.UserIdentity{}).
		Where("user_id IN ?", userIDs).
		Select("user_id").
		Find(&userIdentities).Error
	if err != nil {
		return nil, err
	}

	// 将身份认证结果存入 map，便于查询
	identityMap := make(map[int]bool)
	for _, identity := range userIdentities {
		identityMap[identity.UserID] = true
	}

	// 准备返回值
	var response []customerRes.CusUserDetailsResponse
	for _, user := range users {
		userID := user.ID

		// 构建 CusUserResponse 实例并填充基本信息
		cusUserResponse := customerRes.CusUserDetailsResponse{
			ID:                int(userID),
			Sex:               user.Sex,
			Avatar:            user.Avatar,
			Phone:             user.Phone,
			Address:           user.Address,
			Birth:             user.Birth,
			Research:          user.Research,
			TechnicalVerified: technicalMap[int(userID)],
			IdentityVerified:  identityMap[int(userID)],
		}

		// 填充 Education 信息
		if edu, ok := educationMap[int(userID)]; ok {
			cusUserResponse.Degree = edu.Degree
			cusUserResponse.SchoolName = edu.SchoolName
		}

		// 添加到返回数组
		response = append(response, cusUserResponse)
	}

	return response, nil
}

// UpdateUserInfo 更新用户的个人信息
func (s *AppUserService) UpdateUserInfo(userID int, req customerReq.UpdateUserInfoRequest, avatarPath string) error {
	db := global.GVA_DB.Model(&customer.CusUser{}).Where("id = ?", userID)

	// 准备需要更新的字段
	updateData := map[string]interface{}{}
	if req.Birth != nil {
		birthTime := time.Unix(*req.Birth, 0) // 将 Unix 时间戳转换为 time.Time
		updateData["birth"] = &birthTime      // 使用指针类型
	}
	if req.Address != "" {
		updateData["address"] = req.Address
	}
	if req.Nickname != "" {
		updateData["nickname"] = req.Nickname
	}
	if req.Research != "" {
		updateData["research"] = req.Research
	}
	if avatarPath != "" {
		updateData["avatar"] = avatarPath
	}
	if req.Sex != "" {
		updateData["sex"] = req.Sex
	}

	// 执行更新操作
	if err := db.Updates(updateData).Error; err != nil {
		return err
	}

	return nil
}
func (s *AppUserService) GetUserInfo(userID uint) (*customerRes.UserInfoResponse, error) {
	var user customer.CusUser
	err := global.GVA_DB.Where("id = ?", userID).First(&user).Error
	if err != nil {
		return nil, err
	}

	// 查询 EducationVerification 表中的 SchoolName、IsReviewed 和 IsApproved
	var educationVerification struct {
		SchoolName *string
		IsReviewed bool
		IsApproved bool
	}
	err = global.GVA_DB.Table("education_verifications").
		Select("school_name, is_reviewed, is_approved").
		Where("user_id = ?", userID).
		First(&educationVerification).Error
	fmt.Println("错误消息", err)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}
	var WxBind bool
	if user.Unionid != "" {
		WxBind = true
	} else {
		WxBind = false
	}
	// 构建响应数据
	responseData := customerRes.UserInfoResponse{
		Nickname: user.Nickname,
		//Birth:    user.Birth.Unix(),
		Username: user.Username,
		Birth:    user.Birth,
		Unit:     "",
		Phone:    user.Phone,
		Research: user.Research,
		Address:  user.Address,
		Sex:      user.Sex,
		Avatar:   user.Avatar,
		WxBind:   &WxBind,
	}

	// 判断审核状态并赋值给 Unit
	if educationVerification.SchoolName != nil {
		switch {
		case !educationVerification.IsReviewed:
			responseData.Unit = "审核中"
		case educationVerification.IsReviewed && !educationVerification.IsApproved:
			responseData.Unit = "审核失败"
		case educationVerification.IsApproved:
			responseData.Unit = *educationVerification.SchoolName // 审核通过，正常显示 SchoolName
		}
	}

	return &responseData, nil
}

func (s *AppUserService) GetUser(userID uint) (*customer.CusUser, error) {
	var user customer.CusUser
	err := global.GVA_DB.Where("id = ?", userID).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}
